package com.xysh.aes;

import java.security.MessageDigest;

/**
 * SHA-256
 * Created by lucio on 2019/7/15.
 */
public class EncryptKit {

    private static final String CHARSET = "UTF-8";

    public static String sha256Encrypt(String srcStr) {
        return encrypt("SHA-256", srcStr);
    }

    public static String encrypt(String algorithm, String srcStr) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            byte[] bytes = md.digest(srcStr.getBytes(CHARSET));
            return byte2hex(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String byte2hex(byte[] bytes) {

        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                result.append("0");
            }
            result.append(hex);
        }
        return result.toString();
    }
}
